/*
 * Copyright 2011 Kim Lindhardt Madsen
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package dk.lindhardt.gwt.geie.server.convert;

import dk.lindhardt.gwt.geie.shared.*;
import jxl.CellType;
import jxl.biff.formula.FormulaException;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.biff.FormulaRecord;

/**
 * User: AnAmuser
 * Date: 13-08-11
 * <p/>
 * Converts number formula cells
 */
public class NumberFormulaCellConverterStrategy implements CellConverterStrategy {

   public CellType[] getJXLTypes() {
      return new CellType[] {CellType.NUMBER_FORMULA};
   }

   public Class<? extends dk.lindhardt.gwt.geie.shared.Cell> getGeieType() {
      return dk.lindhardt.gwt.geie.shared.NumberFormulaCell.class;
   }

   public WritableCell convert(dk.lindhardt.gwt.geie.shared.Cell cell, WritableCellFormat cellFormat) {
      dk.lindhardt.gwt.geie.shared.NumberFormulaCell formulaCell = (dk.lindhardt.gwt.geie.shared.NumberFormulaCell) cell;
      Formula formula = formulaCell.getValue();
      String stringFormula = FormulaConverter.convert(formula);
      Position position = cell.getPosition();
      return new FormulaRecord(position.getColumn(), position.getRow(), stringFormula, cellFormat);
   }

   public dk.lindhardt.gwt.geie.shared.Cell convert(jxl.Cell cell, Position position, CellFormatKey cellFormat) {
      jxl.NumberFormulaCell formulaCell = (jxl.NumberFormulaCell) cell;
      try {
         String stringFormula = formulaCell.getFormula();
         Formula formula = FormulaConverter.convert(stringFormula);
         NumberFormulaCell numberFormulaCell = new NumberFormulaCell(formula, position, cellFormat);
         numberFormulaCell.setCalculatedValue(formulaCell.getValue());
         return numberFormulaCell;
      } catch (FormulaException e) {
         return new ErrorCell(null, e.getMessage(), new LabelCell("", position, cellFormat));
      }
   }
}
